#include<iostream>
#include<assert.h>
using namespace std;

template<class T>
class shared_ptr
{
private:    
    T* _ptr;
    int* _pcount;
public:
    shared_ptr(T* ptr)
        :_ptr(ptr)
        ,_pcount(new int(1))
    {}
    
    shared_ptr(const shared_ptr<T>& p)
    {
        assert(_ptr!=p._ptr);
        if((*_pcount)==1)
        {
            //最后一个指针
            delete _ptr;
            delete _pcount;
        }
        else
        {
            (*_pcount)--;
        }
        _ptr=p._ptr;
        _pcount=p._pcount;
        (*_pcount)++;
    }

    shared_ptr<T>& operator=(const shared_ptr<T>& p)
    {
        if(_ptr==p._ptr)return *this;
        if((*_pcount)==1)
        {
            //最后一个指针
            delete _ptr;
            delete _pcount;
        }
        else
        {
            (*_pcount)--;
        } 
        _ptr=p._ptr;
        _pcount=p._pcount;
        (*_pcount)++;
    }

    ~shared_ptr() 
    {
        if((*_pcount)==1)
        {
            delete _ptr;
            delete _pcount;
        }
        else
            (*_pcount)--;
    }
    
    T& operator*()
    {
        return *_ptr;
    }

    T* operator->()
    {
        return _ptr;
    }

    int gets()
    {
        return *_pcount;
    }

};


